package com.fyx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fyx.config.RequestConfig;
import com.fyx.entity.*;
import com.fyx.mapper.SysDictDetailMapper;
import com.fyx.mapper.WechatInfoMapper;
import com.fyx.mapper.WechatUserMapper;
import com.fyx.mapper.WxRequestMapper;
import com.fyx.service.IWeChatService;
import com.fyx.until.HttpUtil;
import com.fyx.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
public class WeChatServiceImpl extends ServiceImpl<SysDictDetailMapper, SysDictDetail>  implements IWeChatService {
    @Autowired
    private WxRequestMapper wxRequestMapper;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Map wxRequest(WxRequest wxRequest, Pageable pageable) {
        Page<WxRequest> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<WxRequest> wrapper =new QueryWrapper<>();
        wrapper.orderBy(true,false,"id");
        IPage<WxRequest> ipage = wxRequestMapper.selectPage(page,wrapper);
        List<WxRequest> list = ipage.getRecords();
        long total = ipage.getTotal();
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public void addWxRequest(WxRequest wxRequest) {
        wxRequest.setCreateTime((int) (new Date().getTime()/1000));
        wxRequest.setCreateUser(SecurityUtils.getCurrentUsername());
        wxRequest.setCreateUserid(SecurityUtils.getCurrentUserId().toString());
        wxRequestMapper.insert(wxRequest);
    }

    @Override
    public void updateWxRequest(WxRequest wxRequest) {
        wxRequest.setUpdateTime((int) (new Date().getTime()/1000));
        wxRequest.setUpdateUser(SecurityUtils.getCurrentUsername());
        wxRequest.setUpdateUserid(SecurityUtils.getCurrentUserId().toString());
        wxRequestMapper.updateById(wxRequest);
    }

    @Override
    public void deleteWxRequest(String[] ids) {
        for(int i=0;i<ids.length;i++){
            wxRequestMapper.deleteById(Integer.parseInt(ids[i]));
        }
    }

    @Autowired
    private WechatInfoMapper wechatInfoMapper;

    @Override
    public Map officialAccounts(WechatInfo wechatInfo, Pageable pageable) {
        Page<WechatInfo> page = new Page<>(pageable.getPageNumber()+1,pageable.getPageSize());
        QueryWrapper<WechatInfo> wrapper =new QueryWrapper<>();
        wrapper.orderBy(true,false,"id");
        IPage<WechatInfo> ipage = wechatInfoMapper.selectPage(page,wrapper);
        List<WechatInfo> list = ipage.getRecords();
        long total = ipage.getTotal();
        Map map =new HashMap();
        map.put("list",list);
        map.put("total",total);
        return map;
    }

    @Override
    public void addOfficialAccounts(WechatInfo wechatInfo) {
        wechatInfo.setCreateTime((int) (new Date().getTime()/1000));
        wechatInfo.setCreateUser(SecurityUtils.getCurrentUsername());
        wechatInfo.setCreateUserid(SecurityUtils.getCurrentUserId().toString());
        wechatInfoMapper.insert(wechatInfo);
    }

    @Override
    public void updateOfficialAccounts(WechatInfo wechatInfo) {
        wechatInfo.setUpdateTime((int) (new Date().getTime()/1000));
        wechatInfo.setUpdateUser(SecurityUtils.getCurrentUsername());
        wechatInfo.setUpdateUserid(SecurityUtils.getCurrentUserId().toString());
        wechatInfoMapper.updateById(wechatInfo);
    }

    @Override
    public void deleteOfficialAccounts(String[] ids) {
        for(int i=0;i<ids.length;i++){
            wechatInfoMapper.deleteById(Integer.parseInt(ids[i]));
        }

    }

    @Autowired
    private WechatUserMapper wechatUserMapper;

    @Override
    public void insertWxUser(String unionid){
        WechatUser wechatUser=new WechatUser();
        UserEntity userEntity=new UserEntity();
        if(unionid!=null) {
            userEntity = mongoTemplate.findOne(new Query().addCriteria(new Criteria("unionid").is(unionid)), UserEntity.class);
            WechatUser  wechatUser1=wechatUserMapper.selectByUnionId(unionid);
            if(userEntity==null){
                if(wechatUser1==null) {
                    wechatUser.setIssend("false");
                    wechatUser.setUnionid(unionid);
                    wechatUser.setTime(new Date().getTime() / 1000);
                    wechatUserMapper.insert(wechatUser);
                }
            }
            else {
                List list=new ArrayList();
                Map map1=new HashMap();
                map1.put("id",100000);
                map1.put("num",18888);
                list.add(map1);
                map1=new HashMap();
                map1.put("id",100001);
                map1.put("num",10);
                list.add(map1);
                if(wechatUser1==null) {
                    wechatUser.setIssend("true");
                    wechatUser.setGameid(userEntity.getUserid());
                    wechatUser.setUnionid(unionid);
                    wechatUser.setTime(new Date().getTime() / 1000);
                    wechatUserMapper.insert(wechatUser);
                    Thread t = new Thread(new Runnable() {
                        public void run() {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("p_id", wechatUser.getGameid());
                            jsonObject.put("title", "关注礼包");
                            jsonObject.put("content", "感谢您关注嘻嘻红中麻将微信公众号，这里可随时反馈任何问题，并且公众号还会不定时发放游戏福利哦~");
                            jsonObject.put("mail_type", 4);
                            jsonObject.put("award", list);
                            JSONObject map = new JSONObject();
                            map.put("cmd", "send_mail");
                            map.put("args", jsonObject);
                            try {
                                HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    t.start();
                }else if(wechatUser1.getIssend().equals("false")){
                    wechatUser1.setIssend("true");
                    wechatUser1.setGameid(userEntity.getUserid());
                    wechatUserMapper.updateUnionId(wechatUser1);
                    Thread t = new Thread(new Runnable() {
                        public void run() {
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("p_id", wechatUser1.getGameid());
                            jsonObject.put("title", "关注礼包");
                            jsonObject.put("content", "感谢您关注嘻嘻红中麻将微信公众号，这里可随时反馈任何问题，并且公众号还会不定时发放游戏福利哦~");
                            jsonObject.put("mail_type", 4);
                            jsonObject.put("award", list);
                            JSONObject map = new JSONObject();
                            map.put("cmd", "send_mail");
                            map.put("args", jsonObject);
                            try {
                                HttpUtil.post(RequestConfig.baseRequestUrl, map.toJSONString(), "utf-8");
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    t.start();
                }
            }
        }
    }
}
